<template>
    <div class="">
        <Breadcrumb :route="routes" />
        <div class="wb-container">
            <div class="mian-content">
                <!-- 头部按钮 -->
                <!-- <div class="header-tabel">
                    <div class="header-left">
                        <el-button class="btnStyle" @click="handleClick('add')" v-has="'roleAdd'">添加</el-button>
                    </div>
                </div> -->
                <Action :options="option" @addClick="handleClick('add')" @removeClick="handelRemoveFun"
                    @loadClick="handelLoadClick"></Action>
                <!-- 角色数据表格 -->
                <el-table v-loading="loading" element-loading-text="加载数据..." ref="multipleTableRef" :data="roleData"
                    style="width: 100%;height:100%;" @selection-change="handleSelectionChange"
                    :header-cell-style="{ background: '#3CB731', color: '#fff', fontSize: '14px', height: '40px', letterSpacing: '2px' }"
                    size="small" border>
                    <template #empty>
                        <el-empty description="暂无数据！" />
                    </template>
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column prop="id" label="ID" align="center" />
                    <el-table-column prop="name" label="角色名称" align="center" />
                    <el-table-column prop="admin_user_id" label="用户ID" show-overflow-tooltip align="center" />
                    <el-table-column fixed="right" label="操作" width="400" align="center" class="right-button">
                        <template #default="{ row }">
                            <el-button class="btn-radius bulecolor" @click="systemClick(row)"
                                v-has="'assignPermissions'">分配权限</el-button>
                            <el-button class="btn-radius warningcolor" @click="getRoleClick(row)"
                                v-has="'getPermissions'">查看角色权限</el-button>
                            <el-tooltip content="修改" effect="dark" placement="top">
                                <el-button class="btn-radius infocolor" @click="handleClick('update', row)"
                                    v-has="'editRole'">
                                    <el-icon>
                                        <EditPen />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" effect="dark" placement="top">
                                <el-button @click="deleteClick(row)" class="btn-radius dangercolor"
                                    v-has="'removeRole'"><el-icon>
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[15, 20, 25, 30]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
            <!-- 编辑弹出框 -->
            <el-dialog v-model="dialogRoleUpdate" title="修改" width="30%">
                <el-form :model="form">
                    <el-form-item label="名称：">
                        <el-input v-model="form.name" autocomplete="off" placeholder="输入角色名称" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button style="border: 1px solid #f0f0f0;" @click="dialogRoleUpdate = false">
                            取消
                        </el-button>
                        <el-button @click="updateRoleName()" type="primary">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 添加弹出框 -->
            <el-dialog v-model="dialogFormVisible" title="添加" width="30%">
                <el-form :model="form">
                    <el-form-item label="名称：">
                        <el-input v-model="form.name" autocomplete="off" placeholder="输入角色名称" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button style="border: 1px solid #f0f0f0;" @click="dialogFormVisible = false">
                            取消
                        </el-button>
                        <el-button type="primary" @click="addRoleName()">确定</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 分配角色权限 -->
            <el-dialog v-model="centerDialogVisible" :title="dialogTitle">
                <el-form :model="form" :label-position="labelPosition">
                    <el-form-item label="权限：" :label-width="formLabelWidth">
                        <div class="custom-tree-node-container">
                            <div class="checkbox-box">
                                <el-checkbox label="全选" v-if="checkAllIsShow" v-model="checkAll"
                                    @change="selectAllChange" />
                                <el-checkbox label="展开" v-model="expandAll" @change="expandAllChange(expandAll)" />
                            </div>
                            <el-tree :data="dataMenu" show-checkbox node-key="id" :expand-on-click-node="true"
                                :default-expand-all="expandAll" :check-on-click-node="false"
                                :default-checked-keys="selectNode" highlight-current style="width:100%;"
                                :check-strictly="isCheck" @check="handleCurrentChecked" ref="treeRef" />
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="getNodeKey()" v-if="roleSystemDetermine">确定</el-button>
                        <el-button @click="roleTreeClose" style="border: 1px solid #f0f0f0;">
                            取消
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import Breadcrumb from '@/components/nav-header'
import Action from "@/components/action";
import { ElTable, ElButton, ElTooltip, ElTree, ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { dealTreeData } from '@/utlis/index'
import { roleList } from '@/api/role/index'
import { roleAdd, roleEdit, roleSystem, getRoleMenu, roleRemove } from '@/api/role/index'
import request from '@/api/request'
import { MenuList } from '@/api/menu'
import { useRouter } from 'vue-router'
const route = useRoute()
const routes = ref()
const dialogFormVisible = ref(false)
const dialogRoleUpdate = ref(false)
const roleId = ref()
const updateRoleId = ref()
const dialogTitle = ref('分配角色权限')
const router = useRouter()
const menuIds = ref()
const form = reactive({
    name: '',
    region: '',
    date1: '',
    date2: '',
    delivery: false,
    type: [],
    resource: '',
    desc: '',
})
const formLabelWidth = ref('120')
const labelPosition = ref('top')
const rolePurview = ref()
const AllroleList = ref(null)
const centerDialogVisible = ref(false)
const roleSystemDetermine = ref(true)
const currentPage = ref(1)
const pageSize = ref(15)
const small = ref(true)
const background = ref(true)
const disabled = ref(false)
const total = ref(0)
const list = reactive({
    limit: 15,
    page: 1
})
const loading = ref(true)
const checkAllIsShow = ref(true)
const dataMenu = ref(null)
const selectNode = ref(null)
const treeRef = ref()
const checkAll = ref(false)
const isCheck = ref(false)
const roleData = ref()
const expandAll = ref(false)
const multipleTableRef = ref()
const selectList = ref([])

const option = reactive({
    shuaxinDisplay: true,
    addDisplay: true,
    editDiaplay: false,
    removeDisplay: true,
    caozuoDisplay: false,
    qiehuanDisplay: false,
    sousuoDisplay: false,
    disabled: true
})
onMounted(() => {
    routes.value = route.matched
    getMenuData()
    getRoleData()
})
const handelRemoveFun = () => {
    ElMessageBox.confirm(
        '确定删除数据',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            for (let i = 0; i < selectList.value.length; i++) {
                try {
                    simulation(selectList.value[i])
                } catch (err) {
                    // console.log(err);
                }
            }
            option.disabled = true
        }).catch(() => {

        })
}
const simulation = async (select) => {
    await roleRemove(select.id).then(res => {
        const { code, data } = res
        if (code == 200) {
            getRoleData()
        }
    })
}
const handelLoadClick = () => {
    getRoleData()
}
const handleSelectionChange = (val) => {
    selectList.value = val
    console.log();
    if (selectList.value.length > 0) {
        option.disabled = false
    } else {
        option.disabled = true
    }
}
const getRoleData = async () => {
    const data = await roleList(list).then(res => {
        const { code, data } = res
        loading.value = false
        if (code == 200) {
            roleData.value = data.data
            total.value = data.total
        }
    }).catch((err) => {
        loading.value = false
    })
}
const handleSizeChange = (val) => {
    list.limit = val
    getRoleData()
}
const handleCurrentChange = (value) => {
    list.page = value
    getRoleData()
}
const handleClick = (type, row) => {
    if (type === 'add') {
        form.name = ''
        dialogFormVisible.value = true
    } else {
        updateRoleId.value = row.id
        form.name = row.name
        dialogRoleUpdate.value = true
    }
}
const updateRoleName = async () => {
    dialogRoleUpdate.value = false
    const update = await roleEdit(updateRoleId.value, { name: form.name })
    const { code, data } = update
    if (code == 200) {
        getRoleData()
    }
}
const addRoleName = async () => {
    dialogFormVisible.value = false
    const add = await roleAdd({ name: form.name })
    const { code, data } = add
    if (code == 200) {
        getRoleData()
    }
}
const deleteClick = (row) => {
    ElMessageBox.confirm(
        '确定删除此项',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await roleRemove(row.id).then(remove => {
                const { code, data } = remove
                if (code == 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getRoleData()
                }
            })
        }).catch(() => {

        })

}
const selectAllChange = () => {
    if (checkAll.value) {
        treeRef.value.setCheckedNodes(dataMenu.value)
        isCheck.value = false
        let nameListHandle = treeRef.value.getCheckedNodes();
        getArrayId(nameListHandle)
    } else {
        treeRef.value.setCheckedNodes([])
    }
}
const expandAllChange = function (isExpand) {
    let nodes = treeRef.value.store.nodesMap;
    for (const node in nodes) {
        nodes[node].expanded = isExpand;
    }
}
const getMenuData = async () => {
    const res = await MenuList()
    const { code, data } = res
    if (code == 200) {
        const array = [...data]
        const dealTreeData = (array) => {
            const data = array.map((item) => ({
                label: item.name,
                id: item.id,
                children: item.children && item.children.length ? dealTreeData(item.children) : null
            }))
            return data
        }
        dataMenu.value = dealTreeData(array)
        const getCheckAllList = (arr) => {
            const list = arr.map((it) => {
                const checked = []
                const checked1 = []
                checked.push({
                    label: it.name,
                    id: it.id
                })
                if (it.children && it.children.length) {
                    let child = it.children.map(item => ({
                        label: item.name,
                        id: item.id
                    }))
                    checked1.push(child)
                }
                return [...checked, ...checked1]
            })
            return list
        }
        let obj = getCheckAllList(array)
        let result = null
        for (let k in obj) {
            let s = obj[k][1]
            result += obj[k][1]?.length
        }
        AllroleList.value = result + Object.keys(dataMenu.value).length

    } else {
        ElMessage({
            type: 'info',
            message: '菜单数据获取失败',
        })
    }
}
const systemClick = (row) => {
    roleSystemDetermine.value = true
    dialogTitle.value = '分配角色权限'
    checkAllIsShow.value = true
    roleId.value = row.id
    getRoleList(roleId.value)
    centerDialogVisible.value = true
}
const handleCurrentChecked = (nodeObj, selectedObj) => {
    let checkedKey = selectedObj.checkedKeys
    let halfChecke = selectedObj.halfCheckedKeys
    menuIds.value = checkedKey
    let checkItem = selectedObj.checkedNodes.length
    if (checkItem != AllroleList.value) {
        checkAll.value = false
    } else {
        checkAll.value = true
    }
}
const getArrayId = (checkedObj) => {
    const updateAllKey = checkedObj.map(item => {
        if (item.length < 0) {
            return
        } else {
            return {
                id: item.id
            }
        }
    })
    const menuData = Object.values(updateAllKey)
    const menuId = []
    const res = menuData.map(item => ({
        id: Object.values(item)
    }))
    res.forEach(item => {
        menuId.push(item.id)
    })
    const data = Object.values(menuId.map(item =>
        Object.values(item)
    ))
    const id = data.map(item => Number(item))
    menuIds.value = id
}
const getNodeKey = async () => {
    let arr = treeRef.value.getCheckedKeys();
    let arr1 = treeRef.value.getHalfCheckedKeys();
    let permissionId = arr.concat(arr1);
    const roleSystemData = await roleSystem({ id: roleId.value, menu_ids: permissionId })
    const { code, data } = roleSystemData
    if (code == 200) {
        ElMessage.success('权限分配成功')
        centerDialogVisible.value = false
    } else {
        ElMessage.error('权限分配失败')
        centerDialogVisible.value = false
    }
}
const roleTreeClose = () => {
    centerDialogVisible.value = false
    checkAll.value = false
}

const getRoleClick = (item) => {
    roleSystemDetermine.value = false
    dialogTitle.value = '查看角色权限'
    checkAllIsShow.value = false
    let roleId = item.id
    getRoleList(roleId)
    centerDialogVisible.value = true
}
const getRoleList = async (roleId) => {
    const List = await getRoleMenu(roleId).then(r => {
        const { code, data } = r
        if (code == 200) {
            rolePurview.value = data
            let childrenData = rolePurview.value.map(item => {
                let child = []
                child.push(item.children)
                return child
            })
            let chlidList = []
            let chlidData = childrenData.map(item => {
                item.forEach(it => {
                    for (const k in it) {
                        chlidList.push(it[k])
                    }
                })
            })
            let setChecked = dealTreeData(chlidList)
            let nodeNumber = setChecked.length + rolePurview.value.length
            if (nodeNumber != AllroleList.value) {
                checkAll.value = false
            } else {
                checkAll.value = true
            }
            treeRef.value.setCheckedNodes(setChecked)
        }
    })
}

</script>

<style lang="less" scoped>
@import '../../style/index.less';

.header-tabel {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
        padding: 10px 0 20px 0;
    }

    .header-left button {
        margin-right: 2px;
    }

    .header-right .xlsx {
        padding: 10px;
        background-color: #ddd;
        margin-left: 5px;
        border: 1px solid #dddddd;
        border-radius: 5px;
    }

    .right-button .el-tooltip .el-button {
        margin-left: 10px;
    }

}

:deep(.el-button) {
    padding: 2px 10px;
    font-size: 12px;
    letter-spacing: 2px;
}

.dialog-footer {
    .el-button {
        padding: 4px 20px;
        font-size: 14px;
    }
}

.btn-radius {
    border-radius: 50px;
    color: #000;
    padding: 6px 10px;
    margin: 10px;
}

.bulecolor {
    background-color: @sidebg-color;
    color: @textColor;
    font-size: 12px;
}

.warningcolor {
    background-color: @waring-color;
    color: @textColor;
    font-size: 12px;
}

.infocolor {
    // background-color: #CDD0D6;
    background-color: @bule-color;
    color: @bg1-color;
    font-size: 14px;
}

.dangercolor {
    background-color: @bg1-color ;
    color: @redColor;
    font-size: 14px;
}


.power-list {
    display: flex;
    flex-direction: column;
}

.is-penultimate>.el-tree-node__content {
    color: #626aef;
}

.el-tree-node.is-expanded.is-penultimate>.el-tree-node__children {
    display: flex;
    flex-direction: row;
}

.is-penultimate>.el-tree-node__children>div {
    width: 25%;
}

.custom-tree-node-container {
    display: flex;
    flex-direction: column;
}

.checkbox-box {
    display: flex;
}

:deep(.el-dialog) {
    header {
        background: rgb(68, 171, 247);
        margin-right: 0;

        .el-dialog__title {
            color: #fff;
        }

        .el-dialog__headerbtn i {
            color: #fff;
        }
    }
}

:deep(.el-dialog__close) {
    color: #fff;
}
</style>
